require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
  _id: 内嵌文档，不生成id
  name: 属性名称
  field: 属性字段
  dtype: 属性数据类型
  len: 属性值长度
  notnullable: 是否可空
  dvalue: 属性默认值
  tag: 属性标签（分组）
  enums: 枚举类型的值范围
*/
var AttrSchema = Schema({
  _id: false,
  name: String,
  field: String,
  dtype: String,
  len: { type: Number, default: 255 },
  notnullable: { type: Boolean, default: false },
  dvalue: Schema.Types.Mixed,
  enums: []
});

/**
  业务模型
  code: 唯一标识
  name: 名字
  instances: 包含的资源
*/
var bizdefSchema = Schema({
  code: { type: String, unique: true },
  name: { type: String },
  desc: { type: String },
  icon: { type: String},
  attrs: [AttrSchema],
  relations: [{ type: Schema.Types.ObjectId, ref: 'Bizrela' }]
})

bizdefSchema.statics = {
  page: async function (query, page, limit) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20

    const total = await Bizdef.count(query)
    let docs = await Bizdef.find(query, {versions: 0}).skip((page) * limit).limit(limit * 1)

    return new Promise((resolve, reject) => {
      resolve(
        {
          pageable: {
            totalElements: total,
            numberOfElements: docs.length,
            totalPages: Math.ceil(total / limit),
            number: page,
            first: page == 0,
            last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
            size: limit,
            fromNumber: page * limit,
            toNumber: page * limit + docs.length
          },
          docs
        }
      )
    })
  }
}

var Bizdef = mongoose.model('Bizdef', bizdefSchema);

module.exports = Bizdef
